import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    redirect: {'name':'welcome'},
    component: Home, children: [
      { path: '/welcome', name: 'welcome', component: Welcome }
    ]
  }

]
const router = new VueRouter({
  routes
})
//挂在路由导航守卫
router.beforeEach((to, from, next) => {
  //to代表将要访问的路径，from代表从哪个路径跳转，next代表一个函数，表示放行
  //next()放行 next("/login")强制跳转
  if (to.path === '/login') return next();
  // 获取token,判断是否包含token，包含则跳转，不包含则返回login
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // 执行跳转
  next()
})

export default router
